package com.lvcoding.sec2.secdemo2.util;


import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JwtUtil {

    // 秘钥,至少32个字符
    private static final String secret = "11111111112222222222333333333366";

    private static final long expire = 1000 * 60;

    public static String createToken(Map<String, Object> map) {

        return Jwts.builder()
                .addClaims(map)
                .signWith(getKey())
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .compact();
    }

    public static Map<String, Object> parseToken(String token) {
        return (Map<String, Object>) Jwts.parserBuilder()
                .setSigningKey(getKey())
                .build()
                .parse(token)
                .getBody();
    }

    public static boolean checkToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(getKey())
                    .build()
                    .parse(token)
                    .getBody();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private static Key getKey() {
        return Keys.hmacShaKeyFor(secret.getBytes());
    }
}
